import { IAppOption } from "../../typings";
import { ZCC_TYPE } from "../../typings/types/common";
import { zcc } from "./util";

// 全局请求封装
// const base_url = "https://recheck.bczcc.com";
const base_url = "https://test-recheck.bczcc.com";
// const base_url = "http://192.168.102.162:8888";
// 前缀
const prefix_open = "/recheck-web";
const prefix_confined = "/recheck-web/confined";
// open
export const requestOpen = (params) => {
  let url = params.url;
  let method = params.method || "GET";
  let data = params.data || {};
  let header = {};

  if (method == "POST") {
    header = {
      "content-type": "application/json",
    };
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: base_url + prefix_open + url,
      method: method,
      header: header,
      data: data,
      success(response) {
        const res = response.data;
        if (response.statusCode == 200) {
          if (response.cookies && response.cookies.length > 0) {
            saveCookie(response.cookies);
          }
          // resolve(res);
          if (res.code === "000") {
            resolve(res);
          } else {
            wx.showToast({
              title: res.desc,
              duration: 2000,
              icon: "none",
            });
            if (res.code === "401") {
              zcc.logout();
            }
          }
        } else {
          switch (response.statusCode) {
            case 404:
              wx.showToast({
                title: "请求地址不存在...",
                duration: 2000,
              });
              break;
            default:
              wx.showToast({
                title: "请重试...",
                duration: 2000,
              });
              break;
          }
        }
      },
      fail(err) {
        console.log(err);
        if (err.errMsg.indexOf("request:fail") !== -1) {
          wx.showToast({
            title: "网络异常",
            icon: "error",
            duration: 2000,
          });
        } else {
          wx.showToast({
            title: "未知异常",
            duration: 2000,
          });
        }
        reject(err);
      },
      complete() {},
    });
  }).catch((e) => {});
};

// confined
export const request = (params) => {
  let url = params.url;
  let method = params.method || "GET";
  let data = params.data || {};
  let header = {};

  if (method == "POST") {
    header = {
      "content-type": "application/json",
    };
  }

  // 获取本地token
  const token = wx.getStorageSync("token");
  const cookie = wx.getStorageSync("Cookie");
  if (token && cookie) {
    header["Authorization"] = "Bearer " + token;
    header["Cookie"] = cookie;
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: base_url + prefix_confined + url,
      method: method,
      header: header,
      data: data,
      success(response) {
        const res = response.data;
        if (response.statusCode == 200) {
          if (res.code === "000") {
            resolve(res);
          } else {
            wx.showToast({
              title: res.desc,
              duration: 2000,
              icon: "none",
            });
            if (res.code === "401") {
              zcc.logout();
            }
          }
        } else {
          switch (response.statusCode) {
            case 401:
              goLogin();
              break;
            case 404:
              zcc.logout();
              wx.showToast({
                title: "请求地址不存在...",
                duration: 2000,
              });
              break;
            default:
              zcc.logout();
              wx.showToast({
                title: "请重试...",
                duration: 2000,
              });
              break;
          }
        }
      },
      fail(err) {
        console.log(err);
        if (err.errMsg.indexOf("request:fail") !== -1) {
          wx.showToast({
            title: "网络异常",
            icon: "error",
            duration: 2000,
          });
        } else {
          wx.showToast({
            title: "未知异常",
            duration: 2000,
          });
        }
        reject(err);
      },
      complete() {},
    });
  }).catch((e) => {});
};

const goLogin = () => {
  if (!getApp<IAppOption>().globalData.isLogin) {
    return;
  }
  zcc.logout();
  wx.showModal({
    title: "提示",
    content: "请登录",
    showCancel: false,
    success(res) {
      setTimeout(() => {
        wx.redirectTo({
          url: "/pages/login/login",
        });
      }, 1000);
    },
  });
};

// 存储cookie
export const saveCookie = (cookies) => {
  var str = cookies.find((item) => item.includes("recheck_ticket"));
  if (!str) return;
  var regTicket = new RegExp("recheck_ticket=" + "(.*?)" + ";", "g");
  var match = str.match(regTicket);
  var token = match && match[0] && match[0].split("=")[1];
  if (token) {
    wx.setStorageSync("token", token);
    wx.setStorageSync("Cookie", cookies.join(";"));
  }
};

const handleRequestSuccess = <T>(
  response: WechatMiniprogram.RequestSuccessCallbackResult<T>
) => {
  if (response.statusCode == 200) {
    if (res.code === "000") {
      resolve(res);
    } else {
      wx.showToast({
        title: res.desc,
        duration: 2000,
        icon: "none",
      });
      if (res.code === "401") {
        zcc.logout();
      }
    }
  } else {
    zcc.logout();
    switch (response.statusCode) {
      case 401:
        goLogin();
        break;
      case 404:
        wx.showToast({
          title: "请求地址不存在...",
          duration: 2000,
        });
        break;
      default:
        wx.showToast({
          title: "请重试...",
          duration: 2000,
        });
        break;
    }
  }
};

/////////////////////////

export const http = async <T>(option: WechatMiniprogram.RequestOption) => {
  let url = option.url;
  let method = option.method || "GET";
  let data = option.data || {};
  let header: WechatMiniprogram.IAnyObject = {};

  if (method == "POST") {
    header = {
      "content-type": "application/json",
    };
  }

  // 获取本地token
  const token = wx.getStorageSync("token");
  console.log(token);
  const cookie = wx.getStorageSync("Cookie");
  if (token && cookie) {
    header["Authorization"] = "Bearer " + token;
    header["Cookie"] = cookie;
  }

  return new Promise<ZCC_TYPE.Data<T>>((resolve, reject) => {
    wx.request({
      url: base_url + prefix_confined + url,
      method: method,
      header: header,
      data: data,
      success(response) {
        const res = response.data as ZCC_TYPE.Data<T>;
        if (response.statusCode == 200) {
          if (res.code === "000") {
            resolve(res);
          } else {
            wx.showToast({
              title: res.desc,
              duration: 2000,
              icon: "none",
            });
            if (res.code === "401") {
              zcc.logout();
            }
          }
        } else {
          switch (response.statusCode) {
            case 401:
              goLogin();
              break;
            case 404:
              zcc.logout();
              wx.showToast({
                title: "请求地址不存在...",
                duration: 2000,
              });
              break;
            default:
              zcc.logout();
              wx.showToast({
                title: "请重试...",
                duration: 2000,
              });
              break;
          }
          reject({ code: "-1", desc: "请求失败" });
        }
      },
      fail(err) {
        console.log(err);
        if (err.errMsg.indexOf("request:fail") !== -1) {
          wx.showToast({
            title: "网络异常",
            icon: "error",
            duration: 2000,
          });
        } else {
          wx.showToast({
            title: "未知异常",
            duration: 2000,
          });
        }
        reject(err);
      },
    });
  });
};
